<?php
/*
CREATE TABLE `emails` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `to` varchar(255) DEFAULT NULL,
  `subject` varchar(255) DEFAULT NULL,
  `message` text,
  `headers` text,
  `timestamp` int(15) DEFAULT NULL,
  `sent` int(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`)
);
*/

#### EMAIL #####################################################################
function email($to, $subject, $message, $headers, $queue = false) {
	if ($queue) {
		$email = model('emails');
		$email->to = $to;
		$email->subject = $subject;
		$email->message = $message;
		$email->headers = $headers;
		$email->timestamp = time();
		$email->create();
	}
	else {
		mail($to, $subject, $message, $headers);
	}
}

#### SEND EMAIL ################################################################
function sendEmail($limit, $delete = true) {
	$emails = model('emails')->find('sent = 0', $limit);
	foreach ($emails as $email) {
		email($email->to, $email->subject, $email->message, $email->headers);
		$email->sent = 1;
		if ($delete) $email->delete();
		else $email->update();
	}
}
?>